package com.salon.server.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.salon.server.entity.Member;
import com.baomidou.mybatisplus.extension.service.IService;
import com.salon.server.entity.User;
import com.salon.server.mapper.MemberMapper;
import com.salon.server.model.MessageType;
import com.salon.server.model.R;
import com.salon.server.model.UserResponse;
import com.salon.server.model.response.MemberResponse;
import org.springframework.stereotype.Service;

/**
* @author Admin
* @description 针对表【member(会员表)】的数据库操作Service
* @createDate 2025-08-27 17:23:30
*/
@Service
public class MemberService extends ServiceImpl<MemberMapper, Member> {

    public R loginValid(Member member) {

        // 根据登录名查询用户
        Member localMember = this.baseMapper.selectOne(new LambdaQueryWrapper<Member>().eq(Member::getName, member.getName()));
        if (localMember == null) {
            return R.fail(MessageType.ACCOUNT_PASSWORD_ERROR);
        }

        // 校验密码
        if (!localMember.getPassword().equals(member.getPassword())) {
            return R.fail(MessageType.ACCOUNT_PASSWORD_ERROR);
        }

        // 校验通过，返回成功
        StpUtil.login(localMember.getId());
        MemberResponse memberResponse = new MemberResponse();
        memberResponse.setToken(StpUtil.getTokenValue());
        localMember.setPassword(null);
        memberResponse.setMember(localMember);
        return R.success(memberResponse);
    }

    public void addBalance(Member member) {

        // 查询会员
        Member localMember = this.baseMapper.selectById(member.getId());
        if (localMember == null) {
            throw new IllegalArgumentException("会员不存在");
        }

        member.setBalance(localMember.getBalance().add(member.getBalance()));

        // 校验通过，增加余额
        this.baseMapper.update(new LambdaUpdateWrapper<Member>()
                .set(Member::getBalance, member.getBalance())
                .eq(Member::getId, member.getId())
        );
    }
}
